<!DOCTYPE html>





<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.7.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.4.0">
  <link rel="mask-icon" href="/images/logo.svg?v=7.4.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.4.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.4.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: '',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="在编写Java程序时经常会用到枚举（后面统一用enum描述）类型，今天我们就来看一下enum中常用到的values()方法。 首先，我们在Eclipse中编写一个简单的类：12345public class EnumTest &amp;#123;    private enum Directions &amp;#123;        NORTH, SOUTH, EAST, WEST    &amp;#125;&amp;#125">
<meta name="keywords" content="java">
<meta property="og:type" content="article">
<meta property="og:title" content="Java中的枚举与values()方法">
<meta property="og:url" content="https://ricky9090.github.io/2015/09/24/java_enum_values/index.html">
<meta property="og:site_name" content="Ricky&#39;s Blog">
<meta property="og:description" content="在编写Java程序时经常会用到枚举（后面统一用enum描述）类型，今天我们就来看一下enum中常用到的values()方法。 首先，我们在Eclipse中编写一个简单的类：12345public class EnumTest &amp;#123;    private enum Directions &amp;#123;        NORTH, SOUTH, EAST, WEST    &amp;#125;&amp;#125">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-06-11T08:46:44.019Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java中的枚举与values()方法">
<meta name="twitter:description" content="在编写Java程序时经常会用到枚举（后面统一用enum描述）类型，今天我们就来看一下enum中常用到的values()方法。 首先，我们在Eclipse中编写一个简单的类：12345public class EnumTest &amp;#123;    private enum Directions &amp;#123;        NORTH, SOUTH, EAST, WEST    &amp;#125;&amp;#125">
  <link rel="canonical" href="https://ricky9090.github.io/2015/09/24/java_enum_values/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>Java中的枚举与values()方法 | Ricky's Blog</title>
  








  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">
  <div class="container use-motion">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Ricky's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">A long way to go.</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-about">
      
    

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-tags">
      
    

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
      <article itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block post">
    <link itemprop="mainEntityOfPage" href="https://ricky9090.github.io/2015/09/24/java_enum_values/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Ricky">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Ricky's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">Java中的枚举与values()方法

          
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2015-09-24 11:10:44" itemprop="dateCreated datePublished" datetime="2015-09-24T11:10:44+08:00">2015-09-24</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2018-06-11 16:46:44" itemprop="dateModified" datetime="2018-06-11T16:46:44+08:00">2018-06-11</time>
              </span>
            
          

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>在编写Java程序时经常会用到枚举（后面统一用enum描述）类型，今天我们就来看一下enum中常用到的values()方法。</p>
<p>首先，我们在Eclipse中编写一个简单的类：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">EnumTest</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">enum</span> Directions &#123;</span><br><span class="line">        NORTH, SOUTH, EAST, WEST</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<a id="more"></a>
<p>在这里，我们定义了一个名叫<strong>Directions</strong>的enum，它其中包含了四个方向。<br>接下来，我们写一个简单的main函数，仅仅是调用values()方法：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    Directions.values();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在Eclipse中，我们点击某个函数、变量时，会跳转到其相应的源码位置。在此处我们尝试点击values()方法，却是没有反应的，这是为什么呢？<br>此外，我们在定义Directions这个enum类型时，使用的是<strong>enum</strong>这个java关键字，那么这里又是如何调用到values()方法的？<br>为此，我们需要了解一下<strong>enum</strong>关键字背后是如何实现的。</p>
<p>最直接的方法就是查阅JDK的文档了，oracle在线文档的地址在这里：<br><a href="http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html" target="_blank" rel="noopener">http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html</a><br>篇幅不是很长，其中恰好有两段说明可以解释我们的两个问题：</p>
<blockquote>
<p>The <strong>enum</strong> declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static <strong>values</strong> method that returns an array containing all of the values of the enum in the order they are declared.</p>
</blockquote>
<p>首先，<strong>enum声明实际上定义了一个类</strong>。因此我们可以通过定义的enum调用其方法。其次，<strong>Java编译器会自动在enum类型中插入一些方法，其中就包括values()</strong>——所以我们的程序在没编译的时候，自然没法查看values()方法的源码了。</p>
<p>那么这个enum是一个什么类呢？接下来还有这样一段说明：</p>
<blockquote>
<p>All <em>enums</em> implicitly extend <strong>java.lang.Enum</strong>. Because a class can only extend one parent (see Declaring Classes), the Java language does not support multiple inheritance of state (see Multiple Inheritance of State, Implementation, and Type), and therefore an enum cannot extend anything else.</p>
</blockquote>
<p>原来，这个枚举实际上是由<strong>java.lang.Enum</strong>这个类实现的，在程序中定义的枚举类型，都会隐式继承此类。并且，由于java中的继承是单继承，所以我们定义的枚举就无法在继承其他类了。<br><br><br>我们来验证一下上面所说的内容：<br>首先在刚才的测试类（在此取名<strong>EnumTest</strong>）开头添加一行import：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.lang.Enum;</span><br></pre></td></tr></table></figure></p>
<p>使用 <em>Ctrl+左键</em> 点击查看其源码，原来是这样一个类：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">Enum</span>&lt;<span class="title">E</span> <span class="keyword">extends</span> <span class="title">Enum</span>&lt;<span class="title">E</span>&gt;&gt;</span></span><br><span class="line"><span class="class">        <span class="keyword">implements</span> <span class="title">Comparable</span>&lt;<span class="title">E</span>&gt;, <span class="title">Serializable</span> </span>&#123;</span><br><span class="line">            ......</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure></p>
<p>查看这个类的实现，果然是没有<strong>values()</strong>方法的。<br>接下来我们通过命令行进入到EnumTest.java文件所在目录，在此使用javac命令编译这个文件：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">javac EnumTest.java</span><br></pre></td></tr></table></figure></p>
<p>通过ls命令查看编译成功后目录中的文件，结果如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">EnumTest$Directions.class</span><br><span class="line">EnumTest.class</span><br><span class="line">EnumTest.java</span><br></pre></td></tr></table></figure></p>
<p>我们可以看到编译器已经为我们生成了<strong>EnumTest$Directions.class</strong>这样一个class文件。<br>通过javap命令，反编译<strong>EnumTest$Directions.class</strong>查看其中的内容：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">javap EnumTest\<span class="variable">$Directions</span>.class</span><br></pre></td></tr></table></figure></p>
<p>结果是这样的：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Compiled from &quot;EnumTest.java&quot;</span><br><span class="line">final class EnumTest$Directions extends java.lang.Enum&lt;EnumTest$Directions&gt; &#123;</span><br><span class="line">  public static final EnumTest$Directions NORTH;</span><br><span class="line">  public static final EnumTest$Directions SOUTH;</span><br><span class="line">  public static final EnumTest$Directions EAST;</span><br><span class="line">  public static final EnumTest$Directions WEST;</span><br><span class="line">  public static EnumTest$Directions[] values();    //编译器插入的方法</span><br><span class="line">  public static EnumTest$Directions valueOf(java.lang.String);</span><br><span class="line">  static &#123;&#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>我们可以看到编译器已经自动为我们插入了<strong>values()</strong>方法了。</p>
<p>最后总结一下：<br>1.java中的enum关键字背后实际是Enum这个类实现的。<br>2.在我们编写自定义的enum时，其中是不含values方法的，再编译java文件时，java编译器会自动帮助我们生成这个方法。</p>

    </div>

    
    
    
        
      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/java/" rel="tag"># java</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/2015/09/18/android_open_view_outline/" rel="next" title="Android中开启布局边界">
                  <i class="fa fa-chevron-left"></i> Android中开启布局边界
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/2015/11/19/java_calendar/" rel="prev" title="Java中获取日期及相应字段">
                  Java中获取日期及相应字段 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
        
        
        
        
      

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Ricky</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">54</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
          
            <a href="/tags/">
          
        
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">标签</span>
        </a>
      </div>
    
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://github.com/ricky9090" title="GitHub &rarr; https://github.com/ricky9090" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
    
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Ricky</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.7.1</div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.4.0</div>

        












        
      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js?v=3.1.0"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="/js/utils.js?v=7.4.0"></script><script src="/js/motion.js?v=7.4.0"></script>
<script src="/js/schemes/pisces.js?v=7.4.0"></script>

<script src="/js/next-boot.js?v=7.4.0"></script>



  





















  

  

  

</body>
</html>
